import os, json, toml
from pydantic import BaseModel

class Question(BaseModel):
    id: str
    question: str
    type: str
    word_limit: int


class Answer(BaseModel):
    id: str
    question: str
    type: str
    word_limit: int
    answer: str


def load_question(question_path: str) -> list[Question]:
    """ 从指定路径加载问题列表 """
    assert os.path.exists(question_path), f"File {question_path} does not exist"
    with open(question_path, 'r') as fp:
        data_list: list = json.load(fp)
    question_list = []
    for item in data_list:
        question = Question.model_validate(item)
        question_list.append(question)
    return question_list


def question2answer(question: Question, answer: str) -> Answer:
    """ 将问题与答案转换为Answer对象 """
    answer_dict = question.model_dump()
    answer_dict['answer'] = answer
    return Answer.model_validate(answer_dict)


def save_answer(answer_list: list[Answer], answer_path: str) -> None:
    """ 将答案列表保存到指定路径 """
    os.path.dirname(answer_path)
    os.makedirs(os.path.dirname(answer_path), exist_ok=True)
    with open(answer_path, 'w') as fp:
        json.dump([answer.model_dump() for answer in answer_list], fp, indent=4)


class Env(BaseModel):
    API_KEY: str
    BASE_URL: str


def load_env(env_path: str) -> Env:
    assert os.path.exists(env_path), f"File {env_path} does not exist"
    with open(env_path, 'r') as fp:
        env_dict = toml.load(fp)
    return Env.model_validate(env_dict)
